package cz.zcu.fav.rat.managed.converter;

import java.util.Iterator;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;

import cz.zcu.fav.rat.beans.User;
import cz.zcu.fav.rat.dataaccess.service.UserService;
import cz.zcu.fav.rat.managed.bean.SpringBeanFactory;

@FacesConverter(value = "userConverter")
public class UserConverter implements Converter
{
	private transient UserService userService;

	public UserService getUserService()
	{
		if (userService == null)
		{
			userService = SpringBeanFactory.getInstance()
					.<UserService> getBean("userService", UserService.class);
		}
		return userService;
	}

	@Override
	public User getAsObject(FacesContext arg0, UIComponent arg1, String arg2)
	{
		Iterator<User> it = getUserService().findByNickname(arg2).iterator();
		if (it.hasNext())
		{
			return it.next();
		}
		return null;
	}

	@Override
	public String getAsString(FacesContext arg0, UIComponent arg1, Object arg2)
	{
		return ((User) arg2).getNickname();
	}

}
